<template>
  <el-row class="p-5 pt-0" @keyup.enter="getSupplierData">

    <el-col v-if="showSearch">
      <el-form :inline="true" :model="search" label-width="70px">
        <el-form-item class="font-black" label="名称">
          <el-input v-model="search.name" :disabled="loading" :size="store.layoutSize" clearable
                    placeholder="请输入供应商名称"
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item class="font-black" label="采购员">
          <el-input v-model="search.buyUser" :disabled="loading" :size="store.layoutSize" clearable
                    placeholder="请输入采购员"
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item class="font-black" label="类型">
          <el-select v-model="search.type" :disabled="loading" :size="store.layoutSize" clearable
                     placeholder="供应商类型"
                     style="width: 120px" @change="getSupplierData">
            <el-option v-for="item in typeData.data" :label="item.dictLabel" :value="item.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item class="font-black" label="创建时间">
          <el-date-picker v-model="date"
                          :disabled="loading"
                          :shortcuts="shortcuts"
                          :size="store.layoutSize"
                          clearable
                          end-placeholder="结束日期"
                          range-separator="-"
                          start-placeholder="开始日期"
                          style="width: 210px"
                          type="daterange"
                          unlink-panels
                          value-format="YYYY-MM-DD"
                          @change="getSupplierData"
          />
        </el-form-item>
        <el-form-item>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space
                     type="primary"
                     @click="getSupplierData">
            <template #icon>
              <el-icon>
                <Search/>
              </el-icon>
            </template>
            查询
          </el-button>
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                     @click="clearSearch">
            <template #icon>
              <el-icon>
                <Refresh/>
              </el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col class="flex justify-between">
      <div>
        <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" auto-insert-space plain
                   type="primary"
                   @click="add">
          <template #icon>
            <el-icon>
              <Plus/>
            </el-icon>
          </template>
          新增
        </el-button>
        <el-button :disabled="search.total === 0 || loading" :size="store.layoutSize" auto-insert-space plain
                   type="warning"
                   @click="download">
          <template #icon>
            <el-icon>
              <Download/>
            </el-icon>
          </template>
          导出
        </el-button>
      </div>
      <div>
        <el-tooltip
            :content="showSearch?'隐藏搜索':'显示搜索'"
            class="box-item"
            effect="dark"
            placement="top"
        >
          <el-button :color="store.getTheme" :size="store.layoutSize" circle
                     @click="showSearch = !showSearch">
            <el-icon>
              <Search/>
            </el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip
            class="box-item"
            content="刷新"
            effect="dark"
            placement="top"
        >
          <el-button :color="store.getTheme" :disabled="loading" :size="store.layoutSize" circle
                     @click="getSupplierData">
            <el-icon>
              <Refresh/>
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </el-col>

    <el-col class="mt-2">
      <el-table v-loading="loading" :data="tableSupplierData.data" :size="store.layoutSize"
                element-loading-text="正在努力加载中..."
                empty-text="无数据" highlight-current-row row-key="id"
                style="width: 100%;"
                table-layout="auto" @row-dblclick="rowClick">

        <el-table-column align="center" fixed="left" label="供应商名称" prop="name" width="250px"/>

        <el-table-column align="center" label="区域" prop="area" width="200px"/>
        <el-table-column align="center" label="详细地址" prop="address" width="200px"/>
        <el-table-column align="center" label="联系人" prop="contacts" width="120px"/>
        <el-table-column align="center" label="电话" prop="phone" width="120px"/>
        <el-table-column align="center" label="邮箱" prop="email" width="160px"/>

        <el-table-column align="center" label="经营模式">
          <template #default="scope">
            <el-tag v-show="scope.row.model" type="info">
              <span v-for="item in modelData.data" v-show="scope.row.model === item.dictValue"
                    :key="item.dictCode">{{ item.dictLabel }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建人" prop="createBy" width="160px"/>

        <el-table-column align="center" label="创建时间" width="180px">
          <template #default="scope">
            {{ moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="备注" prop="remark" width="300px"/>

        <el-table-column align="center" fixed="right" label="操作" width="120px">
          <template #default="scope">
            <el-link :size="store.layoutSize" :style="{color: store.getTheme}" :underline="false" class="text-xs"
                     @click="update(scope.row)">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </el-link>
            <el-link :size="store.layoutSize" :style="{color: store.getTheme}" :underline="false" class="text-xs ml-3"
                     @click="del(scope.row)">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-col>

    <el-col class="mt-3 flex justify-end">
      <el-pagination
          :currentPage="search.pageNum"
          :default-current-page="search.pageNum"
          :page-size='search.pageSize'
          :page-sizes="[10, 20, 50, 100]"
          :pager-count="5"
          :small="store.layoutSize === 'small'"
          :total="search.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
      />
    </el-col>

    <!-- 添加或修改参数配置对话框 -->
    <el-drawer v-model="open" :size="'90%'" :title="title">
      <template #header>
        <h1 class="font-black text-2xl">{{ title }}</h1>
      </template>

      <el-form ref="formRef" :inline="true" :model="form.data" :rules="rules" label-width="80px">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template #title>
              <span class="font-black text-xl">基本信息</span>
            </template>

            <div class="mt-5">
              <el-form-item class="font-black" label="名称" prop="name">
                <el-input v-model="form.data.name" :disabled="readonly" placeholder="请输入供应商名称"
                          style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.contacts)" class="font-black" label="联系人">
                <el-input v-model="form.data.contacts" :disabled="readonly" placeholder="请输入联系人"
                          style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.phone)" class="font-black" label="电话" prop="phone">
                <el-input v-model="form.data.phone" :disabled="readonly" placeholder="请输入电话" style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.email)" class="font-black" label="邮箱" prop="email">
                <el-input v-model="form.data.email" :disabled="readonly" placeholder="请输入邮箱" style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.model)" class="font-black" label="经营模式">
                <el-select v-model="form.data.model" :disabled="readonly" placeholder="请选择经营模式"
                           style="width: 200px">
                  <el-option
                      v-for="item in modelData.data"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item class="font-black" label="类型" prop="type">
                <el-select v-model="form.data.type" :disabled="readonly" placeholder="请选择供应商类型"
                           style="width: 200px">
                  <el-option
                      v-for="item in typeData.data"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.area)" class="font-black" label="区域">
                <el-input v-model="form.data.area" :disabled="readonly" placeholder="请输入区域" style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.address)" class="font-black" label="详细地址">
                <el-input v-model="form.data.address" :disabled="readonly" placeholder="请输入详细地址"
                          style="width: 200px"
                          type="textarea"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.buyUser)" class="font-black" label="采购员">
                <el-select v-model="form.data.buyUser" :disabled="readonly" placeholder="请选择采购员"
                           style="width: 200px">
                  <el-option
                      v-for="item in usersData.data"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.nickName"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.bankDeposit)" class="font-black" label="开户行">
                <el-input v-model="form.data.bankDeposit" :disabled="readonly" placeholder="请输入开户行"
                          style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.accountName)" class="font-black" label="账户名称">
                <el-input v-model="form.data.accountName" :disabled="readonly" placeholder="请输入账户名称"
                          style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.bankCardNo)" class="font-black" label="银行卡号">
                <el-input v-model="form.data.bankCardNo" :disabled="readonly" placeholder="请输入银行卡号"
                          style="width: 200px"/>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.remark)" class="font-black" label="备注">
                <el-input v-model="form.data.remark" :disabled="readonly" style="width: 200px" type="textarea"/>
              </el-form-item>
            </div>

          </el-collapse-item>

          <el-collapse-item name="2">
            <template #title>
              <span class="font-black text-xl">联系人信息</span>
            </template>

            <div class="mt-5">
              <div v-if="!readonly">
                <el-form-item class="font-black" label="联系人">
                  <el-input v-model="contactForm.data.contactName" :disabled="readonly" placeholder="必须填写联系人"
                            style="width: 200px"/>
                </el-form-item>
                <el-form-item class="font-black" label="电话">
                  <el-input v-model="contactForm.data.phone" :disabled="readonly" placeholder="必须填写电话"
                            style="width: 200px"/>
                </el-form-item>
                <el-form-item class="font-black" label="邮箱">
                  <el-input v-model="contactForm.data.email" :disabled="readonly" style="width: 200px"/>
                </el-form-item>
                <el-form-item class="font-black" label="备注">
                  <el-input v-model="contactForm.data.remark" :disabled="readonly" style="width: 200px"
                            type="textarea"/>
                </el-form-item>
              </div>
              <el-row>
                <el-form-item v-show="!readonly">
                  <el-button :color="store.getTheme"
                             :disabled="readonly || !(contactForm.data.contactName && contactForm.data.phone)"
                             auto-insert-space
                             type="primary"
                             @click="addContact">
                    <span>添加到表格</span>
                  </el-button>
                </el-form-item>
                <el-table :data="tableContact.data" border size="large" stripe style="width: 100%">
                  <el-table-column label="联系人" min-width="120" prop="contactName"/>
                  <el-table-column label="电话" min-width="120" prop="phone"/>
                  <el-table-column label="邮箱" min-width="120" prop="email"/>
                  <el-table-column label="备注" min-width="120" prop="remark"/>
                  <el-table-column v-if="!readonly" fixed="right" label="操作" width="70">
                    <template #default="scope">
                      <el-button link size="small" type="primary" @click="delContact(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </div>
          </el-collapse-item>

          <el-collapse-item name="3">
            <template #title>
              <span class="font-black text-xl">品牌信息</span>
            </template>

            <div class="mt-5">
              <div v-show="!readonly">
                <el-form-item class="font-black" label="品牌名">
                  <el-input v-model="brandForm.data.brandName" :disabled="readonly" placeholder="必须填写品牌名"
                            style="width: 200px"/>
                </el-form-item>
                <el-form-item class="font-black" label="供货期">
                  <el-input v-model="brandForm.data.productionTime" :disabled="readonly" placeholder="必须填写供货期"
                            style="width: 200px"/>
                </el-form-item>
                <el-form-item class="font-black" label="备注">
                  <el-input v-model="brandForm.data.remark" :disabled="readonly" style="width: 200px"
                            type="textarea"/>
                </el-form-item>
              </div>
              <el-row>
                <el-form-item v-show="!readonly">
                  <el-button :color="store.getTheme"
                             :disabled="readonly || !(brandForm.data.brandName && brandForm.data.productionTime)"
                             auto-insert-space
                             type="primary"
                             @click="addBrand">
                    <span>添加到表格</span>
                  </el-button>
                </el-form-item>
                <el-table :data="tableBrand.data" border size="large" stripe style="width: 100%">
                  <el-table-column label="品牌名" min-width="120" prop="brandName"/>
                  <el-table-column label="供货期" min-width="120" prop="productionTime"/>
                  <el-table-column label="备注" min-width="120" prop="remark"/>
                  <el-table-column v-if="!readonly" fixed="right" label="操作" width="70">
                    <template #default="scope">
                      <el-button link size="small" type="primary" @click="delBrand(scope.row)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </div>
          </el-collapse-item>

          <el-collapse-item name="4">
            <template #title>
              <span class="font-black text-xl">经营信息</span>
            </template>

            <div class="mt-5">
              <el-form-item v-if="!(readonly && !form.data.cooperationLevel)" class="font-black" label="合作等级">
                <el-select v-model="form.data.cooperationLevel" :disabled="readonly" placeholder="请选择合作等级"
                           style="width: 200px">
                  <el-option
                      v-for="item in cooperationLevelData.data"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.cooperationMode)" class="font-black" label="合作方式">
                <el-select v-model="form.data.cooperationMode" :disabled="readonly" placeholder="请选择合作方式"
                           style="width: 200px">
                  <el-option
                      v-for="item in cooperationModeData.data"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="!(readonly && !form.data.mainProduct)" class="font-black" label="主营产品">
                <el-input v-model="form.data.mainProduct" :disabled="readonly" placeholder="主营产品"
                          style="width: 200px"/>
              </el-form-item>
            </div>
          </el-collapse-item>

        </el-collapse>
      </el-form>

      <template v-if="!readonly" #footer>
        <div class="justify-start flex">
          <el-button :color="store.getTheme" :loading="btnLoading" auto-insert-space type="primary"
                     @click="submitForm(formRef)">
            <span v-if="!btnLoading">保存</span>
            <span v-else>保存中</span>
          </el-button>
          <el-button auto-insert-space @click="open = false">取消</el-button>
        </div>
      </template>
    </el-drawer>

  </el-row>
</template>

<script setup lang="ts">
import {useStore} from "@/store";
import moment from "moment";
import {reactive, ref} from "vue";
import {getDictData} from "@/api/dictData";
import {downloadCustomerSea} from "@/api/customerSea";
import {ElMessageBox, ElNotification, FormInstance, FormRules} from "element-plus";
import {getUsersBySelect} from "@/api/user";
import {
  delSupplier,
  getSupplierBrandById,
  getSupplierContactById,
  getSupplierListApi,
  insertSupplier,
  updateSupplier
} from "@/api/supplier";

const store = useStore()

const activeNames = ref(['1', '2', '3', '4'])

const loading = ref(false)

const showSearch = ref(true)

const date = ref([])

const title = ref('')
const open = ref(false)
const formRef = ref<FormInstance>()

//分页方法
function handleCurrentPageChange(val) {
  search.pageNum = val
  getSupplierData()
}

//页大小切换
function handlePageSizeChange(val) {
  search.pageSize = val
  getSupplierData()
}

//赋值采购人下拉框
const usersData = reactive({
  data: []
})
getUsersBySelect().then(result => {
  usersData.data = result.data.data
})

//赋值供应商类型
const typeData = reactive({
  data: []
})
getDictData({'dictType': 'supplier_type'}).then(result => {
  typeData.data = result.data.data
})

//赋值供应商经营模式
const modelData = reactive({
  data: []
})
getDictData({'dictType': 'supplier_model'}).then(result => {
  modelData.data = result.data.data
})

//赋值供应商合作等级
const cooperationLevelData = reactive({
  data: []
})
getDictData({'dictType': 'supplier_cooperation_level'}).then(result => {
  cooperationLevelData.data = result.data.data
})

//赋值供应商合作方式
const cooperationModeData = reactive({
  data: []
})
getDictData({'dictType': 'supplier_cooperation_mode'}).then(result => {
  cooperationModeData.data = result.data.data
})

const search = reactive({
  name: null,
  buyUser: null,
  type: null,
  startTime: null,
  endTime: null,
  pageNum: 1,
  pageSize: 10,
  total: 0
})

function clearSearch() {
  search.name = null
  search.buyUser = null
  search.type = null
  search.startTime = null
  search.endTime = null
  date.value = []
  getSupplierData()
}

const tableSupplierData = reactive({
  data: []
})
getSupplierData()

function getSupplierData() {
  loading.value = true
  if (date.value && date.value.length > 0) {
    search.startTime = date.value[0]
    search.endTime = date.value[1]
  } else {
    search.startTime = null
    search.endTime = null
  }
  getSupplierListApi(search).then(result => {
    search.total = result.data.data.total
    tableSupplierData.data = result.data.data.list
    loading.value = false
  })
}

const form = reactive({
  data: {},
})
const contactForm = reactive({
  data: {}
})
const tableContact = reactive({
  data: []
})
const brandForm = reactive({
  data: {}
})
const tableBrand = reactive({
  data: []
})

//添加联系人
function addContact() {
  tableContact.data.push(contactForm.data)
  contactForm.data = {}
}

//删除联系人
function delContact(val) {
  ElMessageBox.confirm('您确定要删除<' + val.contactName + '>吗？', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableContact.data.splice(tableContact.data.indexOf(val), 1)
  })
}

//添加品牌
function addBrand() {
  tableBrand.data.push(brandForm.data)
  brandForm.data = {}
}

//删除联系人
function delBrand(val) {
  ElMessageBox.confirm('您确定要删除<' + val.brandName + '>吗？', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    tableBrand.data.splice(tableBrand.data.indexOf(val), 1)
  })
}

//时间选择器快捷选择
const shortcuts = [
  {
    text: '上周内',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

const rules = reactive<FormRules>({
  name: [
    {required: true, message: '供应商名称不能为空', trigger: 'blur'}
  ],
  type: [
    {required: true, message: '请选择供应商类型', trigger: 'blur'}
  ],
  email: [
    {
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"]
    }
  ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur"
    },
  ]
})

const btnLoading = ref(false)

//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('您确定要保存数据吗？', '警告', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        btnLoading.value = true
        form.data.tableContact = tableContact.data
        form.data.tableBrand = tableBrand.data
        if (form.data.id) {
          updateSupplier(form.data).then(result => {
            if (result.data.code === 200) {
              ElNotification({
                message: result.data.msg,
                type: 'success'
              })
              open.value = false
              getSupplierData()
            }
            btnLoading.value = false
          })
        } else {
          insertSupplier(form.data).then(result => {
            if (result.data.code === 200) {
              ElNotification({
                message: result.data.msg,
                type: 'success'
              })
              open.value = false
              getSupplierData()
            }
            btnLoading.value = false
          })
        }
      })
    }
  })
}

//导出数据
function download() {
  ElMessageBox.confirm('您确定要导出<' + search.total + '>条数据吗？', '警告', {
    confirmButtonText: '导出',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    downloadCustomerSea(search).then(response => {
      let disposition = response.headers['content-disposition'];
      //以下部分有需要优化，如后端返回时没有携带文件后缀名,没有.时会有问题等等
      let filename = disposition ? disposition.substring(disposition.indexOf('=') + 1, disposition.indexOf('.')) : "下载文件";
      let newName = decodeURI(escape(filename))
      let extName = disposition.substring(disposition.indexOf('.') + 1)
      let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
      let link = document.createElement("a");
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", false, false);
      link.href = URL.createObjectURL(blob);
      link.download = newName + "." + extName;
      link.style.display = "none";
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(link.href);
    })
  })
}

//添加供应商
function add() {
  tableBrand.data = []
  tableContact.data = []
  readonly.value = false
  form.data = {}
  activeNames.value = ['1', '2', '3', '4']
  form.data.createBy = store.getUser.userName
  title.value = "添加供应商"
  open.value = true
}

const brandLoading = ref(false)
const contactLoading = ref(false)

//修改供应商
function update(val) {
  brandLoading.value = true
  contactLoading.value = true
  getSupplierContactById({id: val.id}).then(result => {
    tableContact.data = result.data.data
    contactLoading.value = false
  })
  getSupplierBrandById({id: val.id}).then(result => {
    tableBrand.data = result.data.data
    brandLoading.value = false
  })
  readonly.value = false
  form.data = val
  form.data.updateBy = store.getUser.userName
  activeNames.value = ['1', '2', '3', '4']
  title.value = "修改供应商"
  open.value = true
}

const readonly = ref(false)

//单元格双击事件
function rowClick(val) {
  brandLoading.value = true
  contactLoading.value = true
  getSupplierContactById({id: val.id}).then(result => {
    tableContact.data = result.data.data
    contactLoading.value = false
  })
  getSupplierBrandById({id: val.id}).then(result => {
    tableBrand.data = result.data.data
    brandLoading.value = false
  })
  readonly.value = true
  form.data = val
  form.data.updateBy = store.getUser.userName
  activeNames.value = ['1', '2', '3', '4']
  title.value = "查看供应商信息"
  open.value = true
}

//删除事件
function del(val) {
  ElMessageBox.confirm('您确定要删除<' + val.name + '>吗？' +
      '这样会删除其所有的联系人与品牌信息', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delSupplier(val.id).then(result => {
      if (result.data.code === 200) {
        ElNotification({
          message: result.data.msg,
          type: 'success'
        })
        getSupplierData()
      }
    })
  });
}
</script>
